package com.ukefu.webim.service.task;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.UKTools;
import com.ukefu.util.sms.SmsService;
import com.ukefu.webim.service.repository.SmsResultRepository;
import com.ukefu.webim.web.model.SmsResult;

@Configuration
@EnableScheduling
public class SmsTask {
	
	@Autowired
	private SmsResultRepository smsRecorRes ;
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Scheduled(fixedDelay= 30000, initialDelay = 20000) // 
    public void task() {
		if(UKDataContext.getContext()!=null && UKDataContext.needRunTask()){
			final String orgi = UKDataContext.SYSTEM_ORGI;
			List<SmsResult> smsResultList = smsRecorRes.findAll(new Specification<SmsResult>(){
				@Override
				public Predicate toPredicate(Root<SmsResult> root, CriteriaQuery<?> query,CriteriaBuilder cb) {
					List<Predicate> list = new ArrayList<Predicate>();  
					
					list.add(cb.equal(root.get("orgi").as(String.class), orgi)) ;
					list.add(cb.isNull(root.get("reachtime").as(Date.class))) ;
					list.add(cb.isNotNull(root.get("serverid").as(String.class))) ;
					list.add(cb.equal(root.get("sendok").as(boolean.class),true)) ;
					
					Date begin = UKTools.getLastDay(1);
					Date end = UKTools.getNextDay(new Date(),1);
					list.add(cb.greaterThanOrEqualTo(root.get("sendtime").as(Date.class), begin)) ;
					list.add(cb.lessThanOrEqualTo(root.get("sendtime").as(Date.class), end)) ;
					Predicate[] p = new Predicate[list.size()];  
				    return cb.and(list.toArray(p));   
				}
			}) ;
			if (smsResultList != null && smsResultList.size() > 0) {
				for(SmsResult smsresult : smsResultList){
					if (!StringUtils.isBlank(smsresult.getSmstype())) {
						SmsService smsService = (SmsService) UKDataContext.getContext().getBean(smsresult.getSmstype());
						if(smsService!=null) {
							try {
								smsService.checkReach(smsresult) ;
								smsRecorRes.save(smsresult) ;
							}catch(Exception ex) {
								ex.printStackTrace();
							}finally {
							}
							
						}
					}
				}
				
			}
		}
	}

}
